package com.zx.tradeclient.ctrl.index5;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zx.base.ctrl.BaseActivity;
import com.zx.base.ctrl.Constant;
import com.zx.base.http.HttpUtils;
import com.zx.base.http.HttpUtils.CallBack;
import com.zx.base.lazylist.ImageLoader;
import com.zx.base.util.URLHelper;
import com.zx.base.widget.LoadMoreListView;
import com.zx.base.widget.LoadMoreListView.OnLoadMoreListener;
import com.zx.base.widget.LoadMoreListViewWithProgress;
import com.zx.tradeclient.R;
import com.zx.tradeclient.app.TradeApp;
import com.zx.tradeclient.entity.CategoryInfo;
import com.zx.tradeclient.entity.GoodsInfo;

public class GoodsList {

	private NewsListAdapter newsListAdapter;
	private LoadMoreListViewWithProgress news_view;
	private LoadMoreListView news_listView;
	private ArrayList<GoodsInfo> newsList = new ArrayList<GoodsInfo>();
	private int page;
	private TradeApp app;
	private ImageLoader imageLoader;
	private Context content;

	public GoodsList(final Context context, View view) {
		content = context;
		page = 1;
		imageLoader = ((TradeApp) context.getApplicationContext()).imageLoader;
		init();
		initview();
		
		app = (TradeApp) context.getApplicationContext();
		news_view = (LoadMoreListViewWithProgress) view.findViewById(R.id.list);
		news_listView = news_view.getListView();
		newsListAdapter = new NewsListAdapter(context, newsList);
		news_listView.setAdapter(newsListAdapter);
		news_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {

				app.product_rating = new CategoryInfo();
				app.categ_index = 8;

				Intent intent = new Intent(context, GoodsEditActivity.class);
				intent.putExtra("act", "edit");
				intent.putExtra("goodid", "" + newsList.get(position).getGoods_id());
				context.startActivity(intent);

			}
		});
		news_listView.setOnLoadMoreListener(new OnLoadMoreListener() {

			@Override
			public void onLoadMore() {
				// TODO 拖动刷新
				page++;
				goodsListTask();
			}
		});
		goodsListTask();
	}

	public void init() {
		((BaseActivity) content).header_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(content, GoodsEditActivity.class);
				intent.putExtra("act", "new");
				content.startActivity(intent);
			}
		});
	}

	private void initview() {

	}

	private static class ViewHolder {
		public ImageView img;
		public TextView title;
		public TextView site;
		public TextView category;
		public TextView value;
		public Button button;
	}

	private class NewsListAdapter extends BaseAdapter {

		private List<GoodsInfo> topics;
		private LayoutInflater mlinflater;

		public NewsListAdapter(Context context, List<GoodsInfo> list) {
			this.mlinflater = LayoutInflater.from(context);
			this.topics = list;
		}

		@Override
		public int getCount() {
			return topics.size();
		}

		@Override
		public Object getItem(int position) {
			return Integer.valueOf(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(final int position, View view, ViewGroup viewGroup) {
			final GoodsInfo topic = topics.get(position);
			if (view == null) {
				view = mlinflater.inflate(R.layout.goods_list_item, null);
				ViewHolder vh = new ViewHolder();
				vh.img = (ImageView) view.findViewById(R.id.list_goods_img);
				vh.title = (TextView) view.findViewById(R.id.list_goods_title);
				vh.site = (TextView) view.findViewById(R.id.list_goods_site);
				vh.value = (TextView) view.findViewById(R.id.list_goods_value);
				vh.category = (TextView) view.findViewById(R.id.list_goods_category);
				vh.button=(Button) view.findViewById(R.id.list_goods_button);
				view.setTag(vh);
			}
			ViewHolder holder = (ViewHolder) view.getTag();
			holder.title.setText(Html.fromHtml("商品名称:" + topic.getGoods_name()));
			holder.site.setText(Html.fromHtml("供货地址:" + topic.getGoods_site()));
			holder.value.setText(Html.fromHtml("商品单价:" + topic.getGoods_value()));
			holder.category.setText(Html.fromHtml("商品类别:" + topic.getGoods_category()));
			holder.button.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// 删除商品
					deleteTask( topic.getGoods_id(),position);
				}
			});
			if (Constant.debug)
				Log.d("href", URLHelper.mPrefixImg+"/" + topic.getGoods_icon());
			imageLoader.DisplayImage(URLHelper.mPrefixImg+"/" +topic.getGoods_icon(), holder.img, R.drawable.default_small);

			return view;
		}
	}

	private void goodsListTask() {

		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "productList");
		map.put("userid", app.user.getId());
		map.put("currentPage", "" + page);
		map.put("rowCountPerPage", "10");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。", Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}
			private void parseJson(JSONObject response) {
				try {
					String currentPage = response.getString("currentPage");
					String totalPage = response.getString("totalPage");
					if (Constant.debug)
						Log.d("stop", currentPage);
					if (Constant.debug)
						Log.d("stop", totalPage);
					if (currentPage.equals(totalPage)) {
						news_listView.loadComplete(false);
					}

					JSONArray list = new JSONArray(response.getString("dataList"));
					for (int i = 0; i < list.length(); i++) {
						GoodsInfo one = new GoodsInfo();
						JSONObject goods = list.getJSONObject(i);
						one.setGoods_id(goods.getString("id"));
						one.setGoods_name(goods.getString("name"));
						one.setGoods_site(goods.getString("city"));
						one.setGoods_value(goods.getString("price"));
						one.setGoods_category(goods.getString("productType"));
						one.setGoods_icon(goods.getString("photo"));
						newsList.add(one);
					}
					newsListAdapter.notifyDataSetChanged();
					news_view.show();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		
	}


	public void refresh(){
		newsList.clear();
		goodsListTask();
	}
	
	private void deleteTask(String id,final int removeid) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("act", "infoDelete");
		map.put("userId", app.user.getId());
		map.put("id", id);
		map.put("type", "1");
		HttpUtils.post(map, new CallBack() {

			@Override
			public void onSuccess(JSONObject response) {
				parseJson(response);

			}

			@Override
			public void onFailure(Throwable e) {
				Toast toast = Toast.makeText(content, "网络超时。",
						Toast.LENGTH_SHORT);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();

			}

			private void parseJson(JSONObject response) {
				try {
					String succeed = response.getString("succeed");
					if(succeed.equals("000")){
						newsList.remove(removeid);
						Toast toast = Toast.makeText(content, "删除成功。",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}else{
						Toast toast = Toast.makeText(content, "删除失败。",
								Toast.LENGTH_SHORT);
						toast.setGravity(Gravity.CENTER, 0, 0);
						toast.show();
					}
					newsListAdapter.notifyDataSetChanged();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
		}
	

}
